﻿using UnityEngine;
using LuaInterface;
using System.Collections.Generic;
using UnityEngine.UI;
using DG.Tweening;
namespace LuaFramework
{
    public class LuaBehaviour : Base
    {
        public string LuaFilePath;
        public string LuaClassName;

        private LuaTable mLuaObject;
        private List<LuaFunction> mLuaFunctions = new List<LuaFunction>(); 
        public LuaTable LuaObject
        {
            get
            {
                return mLuaObject;
            }
        }
        
        void CallLuaFunction(string funcName)
        {
            if (this.mLuaObject == null)
                return;

            LuaFunction func = this.mLuaObject[funcName] as LuaFunction;
            if (func != null)
            {
                func.Call(mLuaObject);
            }
                
        }

        void CallLuaFunction<T>(string funcName, T arg)
        {
            if (this.mLuaObject == null)
                return;

            LuaFunction func = this.mLuaObject[funcName] as LuaFunction;
            if (func != null)
                func.Call<LuaTable, T>(mLuaObject,arg);
        }


        protected void Awake()
        {

            if (string.IsNullOrEmpty(LuaFilePath))
                return;
            Init();
        }

        public void Init()
        {
            
            AppFacade.luaManager.lua.Require(LuaFilePath);
            Init(AppFacade.luaManager.lua.Invoke<LuaTable>(LuaClassName + ".new", true));
        }

        public void Init(LuaTable luaTable)
        {
            mLuaObject = luaTable;
            LuaProperty[] injectProperties = GetComponents<LuaProperty>();
            foreach(var injectProperty in injectProperties)
            {
                injectProperty.Inject(mLuaObject);
            }
            CallLuaFunction<GameObject>("Awake", gameObject);
        }

        protected void OnEnable()
        {
            CallLuaFunction("OnShow");
        }

        protected void Start()
        {
            CallLuaFunction("OnStart");
        }

        protected void OnDisable()
        {
            CallLuaFunction("OnHide");
        }

        void OnDestroy()
        {
            //Debug.Log("~" + name + " was destroy!");
            CallLuaFunction("OnDestroy");
            mLuaObject.Dispose();
            mLuaObject = null; 
        }
    }
}